package cn.rkylin.oms.sysOrder.service;

import cn.rkylin.core.utils.StringUtil;
import cn.rkylin.oms.common.dto.DBLog;
import cn.rkylin.oms.common.utils.DateUtil;
import cn.rkylin.oms.common.utils.LogUtil;
import cn.rkylin.oms.order.domain.EcTrade;
import cn.rkylin.oms.order.service.IOrderService;
import cn.rkylin.oms.sysOrder.dao.ISysOrderDAO;
import cn.rkylin.oms.sysOrder.vo.SysOrderVO;
import cn.rkylin.oms.system.shop.service.IShopService;
import cn.rkylin.oms.system.shop.vo.ShopVO;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 更新系统订单
 * 1：更新非合并和合并前订单平台状态和卖家备注；
 * 2：更新非合并订单系统完成状态；
 * 3：更新合并后订单系统完成状态(子订单平台交易状态都已经是 交易完成或交易取消)；
 * 4：更新合并后订单卖家备注为合并前订单的累加；
 *
 * @author wangxing
 * @version 1.0
 * @created 2017.09.14
 */
@Service("updateSysOrderService")
public class UpdateSysOrderService {

    //待进系统的平台订单数据集
//    private List<EcTrade> tradeList = null;
    //系统合并订单数据集
//    private List<SysOrderVO> sysOrderCombsList = null;

    @Autowired
    private ISysOrderDAO sysOrderDAO;//系统订单数据层

    @Autowired
    private IOrderService orderService;//平台订单服务层

    @Autowired
    private IShopService shopService;

    /**
     * 日志类
     */
    @Autowired
    private LogUtil logUtil;

    /**
     * 平台交易完成状态，用于合并后的系统订单更新平台状态
     */
    private static final String strTradeStatus = "EC_TRADE_FINISHED";

    /**
     * 更新系统订单
     * 1：更新非合并和合并前订单平台状态和卖家备注；
     * 2：更新非合并订单系统完成状态；
     * 3：更新合并后订单系统完成状态(子订单平台交易状态都已经是 交易完成或交易取消)；
     * 4：更新合并后订单卖家备注为合并前订单的累加；
     *
     * @param shopVO
     * @param buyerNick 家昵称 客户ID（手动下载用）
     * @param tradeCode 平台交易号（手动下载用）
     * @throws Exception
     */
    public void updateSysOrder(ShopVO shopVO, String buyerNick, String tradeCode) throws Exception {
        String strShopId = shopVO.getShopId();
        logUtil.info(new DBLog(strShopId, "系统订单自动更新", "跟踪日志", "shopAccount:" + shopVO.getShopAccount() + " 系统订单更新开始---------------------------------------"));
        String OrderLastUpdateTime = "";
        SimpleDateFormat sdfUpdate = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        if (shopVO.getOrderLastUpdateTime() != null) {
            OrderLastUpdateTime = sdfUpdate.format(shopVO.getOrderLastUpdateTime());
        } else {
            logUtil.info(new DBLog(strShopId, "系统订单自动更新", "跟踪日志", " 获取当前店铺平台订单最后更新时间异常"));
            return;
        }

        //获取待更新的平台订单入参
        Map<String, String> tradeMap = new HashMap();
        tradeMap.put("shopId", shopVO.getShopId());
        tradeMap.put("updateTime", OrderLastUpdateTime);
        if (StringUtils.isNotBlank(tradeCode)) {
            tradeMap.put("ecTradeCode", tradeCode);
        }
        if (StringUtils.isNotBlank(buyerNick)) {
            tradeMap.put("ecCustCode", buyerNick);
        }

        //用于更新店铺上的 平台订单最后更新时间
        String currentDate = DateUtil.getCurrentDateStr("yyyy-MM-dd HH:mm:ss");

        //待更新的平台订单数据集
        List<EcTrade> tradeList = new ArrayList<EcTrade>();
//1、获取待更新的平台订单数据集以及对应的系统合并后订单数据集------------------------------------------------------------------------------------------
        tradeList = getTradeList(tradeMap, strShopId);
////----非合并订单处理开始 ---------------------------------------------------------------------------------
        if (tradeList != null && tradeList.size() > 0) {
            logUtil.info(new DBLog(strShopId, "系统订单自动更新", "跟踪日志", "获取待更新非合并平台订单数为:" + String.valueOf(tradeList.size())));
//2、循环平台订单tradeList逐条更新订单状态-----------------------------------------------------
            EcTrade ecTrade = new EcTrade();
            int iRes = 0;
            for (int tradeIndex = 0; tradeIndex < tradeList.size(); tradeIndex++) {
                iRes = 0;
                ecTrade = tradeList.get(tradeIndex);
                logUtil.info(new DBLog(ecTrade.getEcTradeCode(), "系统订单自动更新", "跟踪日志", "非合并订单平台交易号" + ecTrade.getEcTradeCode() + "更新系统订单开始*******************"));
//3、更新非合并和合并前订单平台状态和卖家备注-----------------------------------------------------
                SysOrderVO sysOrderVO = new SysOrderVO();
                try {
                    //更新非合并和合并前订单平台状态和卖家备注
                    sysOrderVO.setTradeCode(ecTrade.getEcTradeCode());
                    sysOrderVO.setTradeStatus(ecTrade.getEcTradeStatus());
                    sysOrderVO.setSalesRemark(ecTrade.getSalesRemark());
                    sysOrderVO.setTbFlagCode(Long.valueOf(ecTrade.getSellerFlag()));
                    iRes = sysOrderDAO.updateByPrimaryKeySelectiveSysOrder(sysOrderVO);
                } catch (Exception ex) {
                    ex.printStackTrace();
                    logUtil.error(new DBLog(ecTrade.getEcTradeCode(), "系统订单自动更新", "跟踪日志", "更新系统订单平台状态和卖家备注异常:" + ex.getMessage()));
                }


                try {
                    //获取对应系统订单
                    Map<String, String> sysOrderMap = new HashMap();
                    sysOrderMap.put("tradeCode", ecTrade.getEcTradeCode());
                    List<SysOrderVO> sysOrderList = sysOrderDAO.selectSysOrderList(sysOrderMap);
                    if (sysOrderList != null && sysOrderList.size() > 0) {
//4、更新非合并订单系统完成状态-----------------------------------------------------
                        //更新订单平台交易状态完成
                        if ("r".equals(sysOrderList.get(0).getOrderStatus()) //已系统发货且未完成
                                && "n".equals(sysOrderList.get(0).getCombStus())
                                && "n".equals(sysOrderList.get(0).getIsCancel())
                                && ("EC_TRADE_FINISHED".equals(ecTrade.getEcTradeStatus())
                                || "EC_TRADE_CANCELED".equals(ecTrade.getEcTradeStatus()))) {
                            iRes = sysOrderDAO.updateSysOrderFinishStatus(sysOrderVO);
                            if (iRes > 0) {
                                //记录日志
                                logUtil.info(new DBLog(ecTrade.getEcTradeCode(), "系统订单自动更新", "", "平台交易完成自动完成系统订单"));
                            }
                        }
                    }
                } catch (Exception ex) {
                    ex.printStackTrace();
                    logUtil.error(new DBLog(ecTrade.getEcTradeCode(), "系统订单自动更新", "跟踪日志", "更新平台交易状态阶段异常:" + ex.getMessage()));
                }
                logUtil.info(new DBLog(strShopId, "系统订单自动更新", "跟踪日志", "非合并订单平台交易号" + ecTrade.getEcTradeCode() + "更新系统订单结束*******************"));
            }
        } else {
            logUtil.info(new DBLog(strShopId, "系统订单自动更新", "跟踪日志", "获取待更新非合并平台订单数为:0"));
        }

////----合并订单处理开始 ---------------------------------------------------------------------------------
        List<SysOrderVO> sysOrderCombsList = new ArrayList<SysOrderVO>();
        sysOrderCombsList = getCombsTradeList(tradeList, strShopId);
        if (sysOrderCombsList != null && sysOrderCombsList.size() > 0) {
            logUtil.info(new DBLog(strShopId, "系统订单自动更新", "跟踪日志", "获取待更新合并平台订单数为:" + String.valueOf(sysOrderCombsList.size())));
//5、循环合并后订单sysOrderCombsList逐条更新订单状态-----------------------------------------------------
            SysOrderVO sysOrderCombVO = new SysOrderVO();
            SysOrderVO sysOrderCombBeforeVO = new SysOrderVO();
            int iRes = 0;
            int iOrderTradeStatus = 0;//合并前订单 交易完成或交易取消 状态
            String strSalesRemarkAdd = "";//卖家备注累加
            for (int sysOrderIndex = 0; sysOrderIndex < sysOrderCombsList.size(); sysOrderIndex++) {
                iRes = 0;
                sysOrderCombVO = sysOrderCombsList.get(sysOrderIndex);
                logUtil.info(new DBLog(sysOrderCombVO.getOrderCode(), "系统订单自动更新", "跟踪日志", "合并订单订单编号" + sysOrderCombVO.getOrderCode() + "更新系统订单开始*******************"));
                iOrderTradeStatus = 0;
                strSalesRemarkAdd = "";
                //获取子订单列表，判断其交易状态以及累加卖家备注
                Map<String, String> sysOrderMap = new HashMap();
                sysOrderMap.put("forderId", sysOrderCombVO.getOrderId());
                sysOrderMap.put("combStus", "b");
                List<SysOrderVO> sysOrderCombBeforeList = sysOrderDAO.selectSysOrderList(sysOrderMap);
                logUtil.info(new DBLog(sysOrderCombVO.getOrderCode(), "系统订单自动更新", "跟踪日志", "合并订单订单编号" + sysOrderCombVO.getOrderCode() + "获取合并前系统订单阶段结束*******************"));
                if (sysOrderCombBeforeList != null && sysOrderCombBeforeList.size() > 0) {
                    //循环子订单判断交易状态,累加卖家备注
                    for (int sysOrderCombBeforeIndex = 0; sysOrderCombBeforeIndex < sysOrderCombBeforeList.size(); sysOrderCombBeforeIndex++) {
                        sysOrderCombBeforeVO = sysOrderCombBeforeList.get(sysOrderCombBeforeIndex);
                        //如果子订单中不存在 交易完成或交易取消 状态
                        if ((!"EC_TRADE_FINISHED".equals(sysOrderCombBeforeVO.getTradeStatus())
                                && !"EC_TRADE_CANCELED".equals(sysOrderCombBeforeVO.getTradeStatus()))) {
                            iOrderTradeStatus = 1;
                        }
                        //卖家备注累加
                        if (StringUtils.isNotBlank(sysOrderCombBeforeVO.getSalesRemark())) {
                            strSalesRemarkAdd = strSalesRemarkAdd + sysOrderCombBeforeVO.getSalesRemark() + ",";
                        }
                    }
//6、更新合并后订单系统完成状态(子订单平台交易状态都已经是 交易完成或交易取消)-----------------------------------------------------
                    try {
                        //合并后订单已系统发货且未完成，对应合并前订单不存在 交易完成或交易取消 的其他状态
                        if ("r".equals(sysOrderCombVO.getOrderStatus()) && iOrderTradeStatus == 0) {
                            //更新合并后订单系统完成状态
                            SysOrderVO sysOrderVO = new SysOrderVO();
                            sysOrderVO.setOrderId(sysOrderCombVO.getOrderId());
                            sysOrderVO.setOrderStatus("z");
                            sysOrderVO.setFinishTime(new Date());
                            sysOrderVO.setTradeStatus(strTradeStatus);
                            iRes = sysOrderDAO.updateByPrimaryKeySelectiveSysOrder(sysOrderVO);
                            if (iRes > 0) {
                                //记录日志
                                logUtil.info(new DBLog(sysOrderCombVO.getOrderCode(), "系统订单自动更新", "", "平台交易完成自动完成系统订单"));
                            }
                        }
                        logUtil.info(new DBLog(sysOrderCombVO.getOrderCode(), "系统订单自动更新", "跟踪日志", "合并订单订单编号" + sysOrderCombVO.getOrderCode() + "更新平台状态阶段结束*******************"));
                    } catch (Exception ex) {
                        ex.printStackTrace();
                        logUtil.error(new DBLog(sysOrderCombVO.getOrderCode(), "系统订单自动更新", "跟踪日志", "更新平台状态阶段异常:" + ex.getMessage()));
                    }
//7、更新合并后订单卖家备注为合并前订单的累加--------------------------------------------------------------------------------
                    try {
                        //更新合并后订单卖家备注为合并前订单的累加
                        SysOrderVO sysOrderVO = new SysOrderVO();
                        sysOrderVO.setOrderId(sysOrderCombVO.getOrderId());
                        if (StringUtils.isNotBlank(strSalesRemarkAdd)) {
                            sysOrderVO.setSalesRemark(strSalesRemarkAdd.substring(0, strSalesRemarkAdd.length() - 1));
                        }
//                        sysOrderVO.setTbFlagCode(1L);
                        iRes = sysOrderDAO.updateByPrimaryKeySelectiveSysOrder(sysOrderVO);
                        logUtil.info(new DBLog(sysOrderCombVO.getOrderCode(), "系统订单自动更新", "跟踪日志", "合并订单订单编号" + sysOrderCombVO.getOrderCode() + "更新合并后卖家备注阶段结束*******************"));
                    } catch (Exception ex) {
                        ex.printStackTrace();
                        logUtil.error(new DBLog(sysOrderCombVO.getOrderCode(), "系统订单自动更新", "跟踪日志", "更新合并后卖家备注阶段异常:" + ex.getMessage()));
                    }
                }
                logUtil.info(new DBLog(sysOrderCombVO.getOrderCode(), "系统订单自动更新", "跟踪日志", "合并订单订单编号" + sysOrderCombVO.getOrderCode() + "更新系统订单结束*******************"));
            }
        } else {
            logUtil.info(new DBLog(strShopId, "系统订单自动更新", "跟踪日志", "获取待更新合并平台订单数为:0"));
        }

        try {
            // 更新最后执行时间
            if (StringUtils.isBlank(tradeCode) && StringUtils.isBlank(buyerNick)) {
                ShopVO shopUpdate = new ShopVO();
                shopUpdate.setShopId(strShopId);
                shopUpdate.setOrderLastUpdateTime(StringUtil.strToDateTime(currentDate));
                shopService.update(shopUpdate);
                logUtil.info(new DBLog(strShopId, "系统订单自动更新", "跟踪日志", "更新当前店铺平台订单最后更新时间结束---------------------------------------"));
            }
        } catch (Exception ex) {
            ex.printStackTrace();
            logUtil.error(new DBLog(strShopId, "系统订单自动更新", "跟踪日志", "更新当前店铺平台订单最后更新时间异常:" + ex.getMessage()));
        }
    }

    /**
     * 获取待更新的平台订单数据集
     *
     * @param reqMap
     * @param strShopId
     * @return
     * @throws Exception
     */
    private List<EcTrade> getTradeList(Map<String, String> reqMap, String strShopId) throws Exception {
        List<EcTrade> tradeList = new ArrayList<EcTrade>();
        try {
            if (reqMap != null && reqMap.size() > 0) {
                tradeList = orderService.selectChangeTradeList(reqMap);
            }
        } catch (Exception ex) {
            ex.printStackTrace();
            tradeList = null;
            logUtil.error(new DBLog(strShopId, "系统订单自动更新", "跟踪日志", "获取待更新平台订单异常:" + ex.getMessage()));
        }

        return tradeList;
    }

    /**
     * 获取待更新的平台订单对应的系统 合并订单 数据集
     *
     * @param tradeList
     * @param strShopId
     * @return
     * @throws Exception
     */
    private List<SysOrderVO> getCombsTradeList(List<EcTrade> tradeList, String strShopId) throws Exception {
        List<SysOrderVO> sysOrderCombsList = new ArrayList<SysOrderVO>();
        try {
            if (tradeList != null && tradeList.size() > 0) {
                //接口表订单平台交易号累加拼串，用于获取系统合并订单入参
                List<String> tradeCodeAddList = new ArrayList<String>();
                for (int tradeIndex = 0; tradeIndex < tradeList.size(); tradeIndex++) {
                    tradeCodeAddList.add(tradeList.get(tradeIndex).getEcTradeCode());
                }
                Map<String, Object> TradeCodeAddMap = new HashMap();
                TradeCodeAddMap.put("trade_code", tradeCodeAddList);
                //获取当前平台订单在系统中是合并前系统订单的合并后系统订单数据集
                sysOrderCombsList = sysOrderDAO.selectCombSysOrderListByTradeCode(TradeCodeAddMap);
            } else {
                sysOrderCombsList = null;
            }

        } catch (Exception ex) {
            ex.printStackTrace();
            sysOrderCombsList = null;
            logUtil.error(new DBLog(strShopId, "系统订单自动更新", "跟踪日志", "获取待更新平台订单对应的系统合并订单异常:" + ex.getMessage()));
        }

        return sysOrderCombsList;
    }
}
